/**
 * @description: 钉钉授权登录及用户信息获取 service
 * @version: 0.0.1
 * @author: z..
 * @Date: 2023-06-12 18:16:39
 */

import { Config, ScopeEnum } from '@midwayjs/decorator';
import { Provide, Inject, Scope, httpError } from '@midwayjs/core';
import { Context } from '@midwayjs/koa';
import { ApiDingtalk } from '../utils/api.dingtalk';
import { OapiDingtalk } from '../utils/oapi.dingtalk';
import { DingtalkAuthService } from "./dingtalk.auth.service"
import { UserRecordsModel } from "../entity/user_records.method";
import { AppConfigModel } from "../entity/app_config.method";
import { UserRoleService } from "./user.role.service"


@Provide()
@Scope(ScopeEnum.Request, { allowDowngrade: true })
export class UserService {

  @Inject()
  ctx: Context;

  @Config('dingtalkAuthConfig')
  dingtalkAuthConfig: any;

  @Config('appConfig')
  appConfig: any;

  @Inject()
  ApiDingtalk: ApiDingtalk;

  @Inject()
  OapiDingtalk: OapiDingtalk;

  @Inject()
  UserRecordsModel: UserRecordsModel;

  @Inject()
  AppConfigModel: AppConfigModel;

  @Inject()
  DingtalkAuthService: DingtalkAuthService;

  @Inject()
  UserRoleService: UserRoleService;

  /**
  * 查询用户在企业中的详细信息
  * @returns 
  */
  async getUserDetails(): Promise<any> {
    const { ctx } = this;
    const userInfo = ctx.userInfo;

    if (userInfo.dept_id_list) {
      return {
        nick: userInfo.nick,
        avatar_url: userInfo.avatar_url,
        dept_id_list: userInfo.dept_id_list,
        // is_admin: userInfo.is_admin || 0,
        role_code: userInfo.role_code || "",
        user_status: userInfo.user_status,
      };
    }

    //  获取apptoken
    const appToken = await this.DingtalkAuthService.getAppToken();
    if (!appToken || !appToken.success) throw new httpError.BadRequestError("获取应用token失败");
    //  获取用户详细信息
    const userDetails = await this.OapiDingtalk.queryUserDetails(userInfo.user_id, appToken.accessToken);
    if (!userDetails || !userDetails.success) throw new httpError.BadRequestError("获取用户详情失败");
    //  获取用户部门信息
    let dept_arr = [];
    for (let i = 0; i < userDetails.dept_id_list.length; i++) {
      const element = userDetails.dept_id_list[i];
      const deptDetails = await this.OapiDingtalk.queryDepartmentDetails(element, appToken.accessToken);
      deptDetails.success ? dept_arr.push(deptDetails.name) : ""
    }
    // 更新用户详情信息
    await this.UserRecordsModel.updateUserDetails({
      id: userInfo.id,
      nick: userDetails.name || userInfo.nick,
      deptIdList: userDetails.dept_id_list.length ? userDetails.dept_id_list.join(",") : "",
      isAdmin: userDetails.admin ? 1 : 0,
      userTitle: userDetails.title || "",
      deptNameList: dept_arr.join(","),
      otherInfo: JSON.stringify(userDetails),
    });
    //  获取更新后的用户数据
    const userRes = await this.UserRecordsModel.getUserById(userInfo.id);

    return {
      nick: userRes[0].nick,
      avatar_url: userRes[0].avatar_url,
      dept_id_list: userRes[0].dept_id_list || "",
      // is_admin: userRes[0].is_admin || 0,
      role_code: userRes[0].role_code || "",
      user_status: userRes[0].user_status,
    };
  }

  /**
   * 根据unionId 查询用户信息
   * @param {*} unionId 
   */
  async getUserByUnionId(unionId: string): Promise<any> {
    try {
      const _user = await this.UserRecordsModel.getUserUnionIdAndRole(unionId);
      if (!_user || !_user.length) return { success: false, userInfo: null };
      return { success: true, userInfo: _user[0] };
    } catch (error) {
      return { success: false, userInfo: null };
    }
  }

  /**
   * 根据unionId 查询用户信息和角色信息
   * @param {*} unionId 
   */
  async getUserByUnionIdAndRole(unionId: string): Promise<any> {
    try {
      const _user = await this.UserRecordsModel.getUserUnionIdAndRole(unionId);
      if (!_user || !_user.length) return { success: false, userInfo: null };
      return { success: true, userInfo: _user[0] };
    } catch (error) {
      return { success: false, userInfo: null };
    }
  }

  /**
   * 获取部门列表
   * @param {*} deptId 
   * @returns 
   */
  async getDeptLists(deptId: any): Promise<any> {
    const appToken = await this.DingtalkAuthService.getAppToken();
    if (!appToken || !appToken.success) throw new httpError.BadRequestError("获取应用token失败");

    //  获取部门树
    return await this.OapiDingtalk.queryDepartmentList(deptId || 1, appToken.accessToken);
  }

  /**
   * 获取部门用户基础信息
   * @param {*} deptId 
   * @returns 
   */
  async getDeptUserLists(deptId: any): Promise<any> {
    const appToken = await this.DingtalkAuthService.getAppToken();
    if (!appToken || !appToken.success) throw new httpError.BadRequestError("获取应用token失败");

    //  获取部门用户基础信息
    return await this.OapiDingtalk.queryUserListsimple(deptId, appToken.accessToken);
  }


  /**
   * 管理员-用户管理
   * @param {*} params 
   * @returns 
   */
  async getUserList(params: any): Promise<any> {
    const { pageSize, pageNum, searchKey } = params;
    const total = await this.UserRecordsModel.getTotalNum(searchKey);
    let res = {
      total: total[0].num,
      lists: []
    }

    if (total[0].num) {
      const resList = await this.UserRecordsModel.getDataByPage(pageNum, pageSize, searchKey);
      res.lists = resList;
    }
    return res;
  }

  /**
   * 更新用户信息
   * @returns 
   */
  async updateUserById(params: any): Promise<any> {
    const { id, key, value } = params;
    // const keyArr = ["is_admin", "user_status"];
    // if (!keyArr.includes(key)) throw new httpError.BadRequestError("key类型错误");

    return await this.UserRecordsModel.updateUserById({ id, key, value });
  }

  /**
   * 获取用户列表
   */
  async getUserLists(searchKey: any): Promise<any> {
    return await this.UserRecordsModel.getAllUserLists(searchKey);
  }

  /**
   * 更新用户工时金额
   * @param params 
   * @returns 
   */
  async updateUserHoursAmount(params: any): Promise<any> {
    return await this.UserRecordsModel.updateUserHoursAmount(params);
  }

  /**
   * 更新用户角色信息
   * @param params 
   * @returns 
   */
  async updateUserRoleRecords(params: any): Promise<any> {
    return await this.UserRoleService.updateUserRoleRecords(params);
  }
}